<template>
  <div class="dashboard-editor-container">

    <!--    <el-card>-->
    <el-row v-loading="loading" :gutter="40">
      <el-col v-if="admin" :span="10">

        <div class="dashboard-editor-container-patient-list">
          <div
            v-for="(item,index) in patientDistribution.slice(0,4)"
            :key="item.t"
            :style="{border:`1px solid ${defaultColors[index]}`}"
            class="dashboard-editor-container-patient-list-item"
            @click="clickOnStageItem(item)"
          >
            <el-button>{{ item.stageName }}</el-button>
            <p class="dashboard-editor-container-patient-list-number">{{ item.stageCount }}</p>
          </div>

        </div>
        <div class="dashboard-editor-container-patient-list">
          <div
            v-for="(item,index) in patientDistribution.slice(4,7)"
            :key="item.t"
            :style="{border:`1px solid ${defaultColors[index+3]}`}"
            class="dashboard-editor-container-patient-list-item"
            @click="clickOnStageItem(item)"
          >
            <el-button>{{ item.stageName }}</el-button>
            <p class="dashboard-editor-container-patient-list-number">{{ item.stageCount }}</p>
          </div>
        </div>

        <el-divider />

        <h2 class="chart-wrapper-title">用户分布总览饼图</h2>
        <div class="chart-wrapper">
          <pie-chart :patient-distribution="patientDistribution" />
        </div>

      </el-col>
      <el-col :span="14">
        <el-card style="min-height:60vh;">
          <!--          <el-date-picker-->
          <!--            v-model="value1"-->
          <!--            placeholder="选择日期"-->
          <!--            type="date"-->
          <!--            @change="onChange"-->
          <!--          />-->

          <div class="patients-wrapper">

            <el-row>
              <el-col :span="4">
                <h2>日程</h2>
              </el-col>
              <el-col :span="20">
                <div v-if="admin" class="coach-filter">
                  <el-form inline>
                    <el-form-item label="教练">
                      <el-select v-model="selectedCoach" clearable placeholder="请选择教练" @change="onCoachChanged">

                        <el-option
                          v-for="(item,index) in coaches"
                          :key="'coach-item-'+index"
                          :label="item.userName"
                          :value="item.userId"
                        />
                      </el-select>
                    </el-form-item>
                  </el-form>
                </div>
              </el-col>
            </el-row>
            <div class="week-filter">

              <div
                v-for="item in weeks"
                :key="'week-item-'+item.day"
                :class="{'checked':curWeekday && item.day === curWeekday.day}"
                class="week-filter-item"
                @click="clickOnWeekday(item)"
              >
                <span>{{ item.weekday }}</span>
                <span>{{ item.day }}</span>
              </div>
            </div>

            <div v-if="tableData && tableData.length>0" class="next-indicator">
              <span>下一位：</span>
              <span>倒计时：{{ nextRemainingTime }}</span>
            </div>
            <el-table
              v-loading="patientLoading"
              :data="tableData"
              :show-header="false"
              max-height="60vh"
              style="width: 100%"
            >
              <el-table-column
                label="时间"
              >
                <template slot-scope="scope">
                  <span>{{ scope.row.startTime }} - {{ scope.row.endTime }}</span>
                </template>

              </el-table-column>
              <el-table-column
                label="姓名"
                prop="nickName"
              />
              <el-table-column
                label="阶段"
                prop="stageInfo"
              />
              <!--              <el-table-column label="教练名称" prop="coachName"></el-table-column>-->
              <el-table-column
                label="学校"
                prop="school"
              />
              <el-table-column
                fixed="right"
                label="操作"
                width="100"
              >
                <template slot-scope="scope">
                  <el-link type="primary" @click="jump(scope.row)">立即前往></el-link>
                </template>
              </el-table-column>
            </el-table>

            <!--            <el-pagination-->
            <!--              layout="prev, pager, next"-->
            <!--              :total="tableTotal"-->
            <!--            />-->
          </div>

          <!--          <div v-if="week">星期{{ week }}</div>-->
        </el-card>

        <el-card style="margin-top:30px;">
          <GroupWeightSetting />
        </el-card>
      </el-col>
    </el-row>

    <!--    </el-card>-->
  </div>
</template>

<script>
import PieChart from './components/PieChart'
import { GetHomepageCoachName, GetReservedPatientsList, GetUserStage } from '@/api/api'
import { mapGetters } from 'vuex'
import GroupWeightSetting from './components/GroupWeightSetting'
import dayjs from 'dayjs'
export default {
  name: 'DashboardAdmin',
  components: {
    PieChart,
    GroupWeightSetting
  },
  data() {
    return {
      patientDistribution: [],
      value1: '',
      tableData: [],
      tableTotal: 0,
      loading: false,
      patientLoading: false,
      weeks: [],
      curWeekday: null,
      coaches: [],
      selectedCoach: null,
      timer: null,
      nextRemainingSeconds: 0,
      defaultColors: [
        'firebrick',
        'darkkhaki',
        'mediumseagreen',
        'coral',
        'lightseagreen',
        'skyblue',
        'orchid',
        'palevioletred'

      ]
    }
  },
  computed: {
    ...mapGetters([
      'admin',
      'userId'
    ]),
    week() {
      return new Date(this.value1).getDay() || ''
    },
    nextRemainingTime() {
      if (this.nextRemainingSeconds <= 0) {
        return '00:00:00'
      }

      const hour = Math.floor(this.nextRemainingSeconds / 60 / 60)
      let minute = Math.floor((this.nextRemainingSeconds - hour * 60 * 60) / 60)
      let seconds = this.nextRemainingSeconds - hour * 60 * 60 - minute * 60

      minute = minute < 10 ? '0' + minute : minute
      seconds = seconds < 10 ? '0' + seconds : seconds
      return `${hour}:${minute}:${seconds}`
    }

  },
  mounted() {
    this.weeks = this.generateWeekData()
    this.curWeekday = this.weeks[0]
    this.getUserStage()
    if (this.admin) {
      this.getCoaches()
    } else {
      this.selectedCoach = this.userId
    }
    this.getPatients()
  },
  beforeDestroy() {
    this.killTimer()
  },
  methods: {
    async getUserStage() {
      try {
        if (this.loading) {
          return
        }
        this.loading = true
        const res = await GetUserStage()
        this.loading = false
        this.patientDistribution = res.data.rows
      } catch (e) {
        console.error(e)
      }
    },

    clickOnStageItem(item) {
      const { stageName } = item

      this.$router.push(`/patient-list/index?stage=${stageName}`)
    },
    clickOnWeekday(week) {
      // console.log(week)
      this.curWeekday = week
      this.getPatients()
    },
    // async onChange(time) {
    //   // eslint-disable-next-line
    //   const res = await GetHomepageCoach(new Date(time).getDay())
    //
    //   console.log(res)
    // },
    onCoachChanged() {
      this.getPatients()
    },

    async getPatients() {
      try {
        if (this.patientLoading) {
          return
        }
        this.patientLoading = true
        const { data } = await GetReservedPatientsList({
          pageNum: 1,
          pageSize: 10,
          curDate: this.curWeekday.date,
          nickName: this.selectedCoach ? this.selectedCoach : '',
          coachId: this.selectedCoach
        })
        this.patientLoading = false
        const { total, rows, code, msg } = data
        console.log('get list with ', code, msg, total, rows)
        if (code !== 200) {
          this.$message.error(msg)
          return
        }
        this.tableData = rows
        this.tableTotal = total

        // get the newest time

        console.log('====== dashboard rows', rows)
        const now = this.$dayjs(new Date())
        rows.forEach(item => {
          const then = this.$dayjs(`${this.curWeekday.date} ${item.startTime}`)
          if (then.isAfter(now)) {
            const seconds = Math.abs(now.unix() - then.unix())
            this.nextRemainingSeconds = seconds
            console.log('===== seconds', seconds)
            this.startTimer()
          } else {
            this.nextRemainingSeconds = 0
            this.killTimer()
          }
        })
      } catch (e) {
        this.patientLoading = false
        console.error(e)
      }
    },

    startTimer() {
      if (this.timer) {
        this.killTimer()
      }
      this.timer = setInterval(() => {
        this.nextRemainingSeconds--
      }, 1000)
    },
    killTimer() {
      clearInterval(this.timer)
      this.timer = null
    },
    async getCoaches() {
      try {
        const res = await GetHomepageCoachName()
        const { code, msg, data } = res.data
        console.log('get coaches', code, msg, data)
        if (code !== 200) {
          this.$message.error(msg)
          return
        }
        this.coaches = data
      } catch (e) {
        this.patientLoading = false
        console.error(e)
      }
    },

    generateWeekData() {
      // const _dateFormat = (date, fmt) => {
      //   console.log('date format with date', date)
      //   const y = date.getFullYear() // 年
      //   const m = date.getMonth() + 1 // 月
      //   const d = date.getDate() // 日
      //
      //   return `${y}${fmt}${m < 10 ? '0' + m : m}${fmt}${d < 10 ? '0' + d : d}`
      // }

      // const date = new Date()
      const currentDate = dayjs()
      // let w = currentDate.getDay() // 当前星期 0-6
      // const y =  currentDate.getFullYear() // 当前年
      // const m = currentDate.getMonth() + 1 // 当前月
      // const d = currentDate.getDate() // 当前日期

      const week = []

      const numWeekArr = ['周日', '周一', '周二', '周三', '周四', '周五', '周六']
      for (let i = 0; i < 7; i++) {
        const newDate = currentDate.add(i, 'day')
        // console.log('new Date', newDate)
        // let day = d + i
        // day = day < 10 ? '0' + day : day
        // const month = m < 10 ? '0' + m : m
        // const newDate = new Date(`${y}-${month}-${day}`)
        // const str = _dateFormat(newDate, '-')
        week.push({
          day: newDate.format('DD'),
          date: newDate.format('YYYY-MM-DD'),
          weekday: numWeekArr[newDate.format('d')]
        })
      }
      return week
    },
    jump(row) {
      this.$router.push(`/patient-detail/index?id=${row.userId}`)
    }
  }
}
</script>

<style lang="scss" scoped>
@import "~@/styles/variables.scss";

.dashboard-editor-container {
  padding: 20px;
  min-height: 80vh;
  //background-color: #eee;
  //background-color: rgb(240, 242, 245);
  position: relative;
  background-color: #f9f9f9;

  .chart-wrapper {
    padding: 16px 16px 0;
    margin-bottom: 32px;
    min-height: 20vh;
  }
}

.dashboard-editor-container-patient-list {
  display: flex;
  flex-wrap: wrap;
  //justify-content: space-between;
  //margin-bottom: 110px;
  justify-content: center;
}

.dashboard-editor-container-patient-list-item {
  width: 100px;
  background-color: #fff;
  height: 100px;
  border: 1px solid palegoldenrod;
  border-radius: 10px;
  text-align: center;
  margin: 0 20px 20px 20px;

  p {
    margin-top: 0;
  }

  button {
    margin: 10px 0 5px;
  }
}

.chart-wrapper-title {
  margin-top: 110px;
  color: #333333;
  text-align: center;
  margin-bottom: 15px;
}

.patients-wrapper {
  h2 {
    margin-top: 5px;
  }
}

.week-filter {
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
  border-top: 1px solid #eee;

  .week-filter-item {
    flex-direction: column;
    align-items: center;
    justify-content: center;
    text-align: center;
    //min-width:
    cursor: pointer;
    transition: all 0.2s linear;
    margin-right: 10px;
    border: 1px solid transparent;
    border-radius: 4px;

    &:hover {
      //border: 1px solid #ccc;
      background-color: #f2f2f2;

      span {
        font-weight: bold;
        color: #ccc;
      }
    }

    &.checked {
      background-color: $menuActiveText;

      span {
        color: #ffffff;

        &:first-child {
          color: #ffffff;
        }
      }
    }

    span {
      padding: 10px 20px;
      display: block;
      color: #333333;
      font-size: 16px;

      &:first-child {
        color: #ccc;
        font-size: 14px;
      }
    }
  }
}

.next-indicator {
  margin: 10px;
}

@media (max-width: 1024px) {
  .chart-wrapper {
    padding: 8px;
  }
}
</style>
